﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Web;
using YuFeng.Utils;

namespace YuFeng.Web.Helpers
{
    public class FileObject
    {
        public string ID { get; set; }
        public string Name { get; set; }
        public string ContentType { get; set; }
        public double? Size { get; set; }
        public string PublicUrl { get; set; }
        //public string TempUrl { get; set; }
    }
    public class FilesHelper
    {
        private static string _dir = ConfigurationManager.AppSettings["FilePath"];
        private static string _rootDir = HttpContext.Current.Server.MapPath(_dir);
        private static string GetSeriesFileName()
        {
            return Guid.NewGuid().ToString("N");
        }/// <summary>
        /// 删除指定文件及相关记录
        /// 后续需要记录日志
        /// </summary>
        /// <param name="storageRoot"></param>
        /// <param name="bucket"></param>
        /// <param name="fileID"></param>
        private static void DeleteFile(string rootDir, string fileID, string folder)
        {
            // 删除文件
            string filePath = GetFilePath(rootDir, folder, fileID);
            if (File.Exists(filePath))
            {
                var info = new FileInfo(filePath);
                File.Delete(filePath);
            }
        }
        private static string GetFilePath(string root, string folder, string fileID)
        {
            string newPath = Path.Combine(root, folder, fileID);
            return newPath;
        }
        private static string GetFileUrl(string root, string folder, string fileID)
        {
            string newPath = root + "/";
            if (!string.IsNullOrEmpty(folder))
            {
                newPath += folder + "/";
            }
            newPath += fileID;
            return newPath;
        }
        public static string GetNewsTitleImg(string fileID)
        {
            if (string.IsNullOrEmpty(fileID))
            {
                return "/Areas/Admin/Content/images/default-img.png";
            }
            string folder = AppConst.NewsTitleImgFold;
            return GetFileUrl(_dir, folder, fileID);
        }
        public static string GetProductImg(string fileID)
        {
            if (string.IsNullOrEmpty(fileID))
            {
                return "/Areas/Admin/Content/images/default-img.png";
            }
            string folder = AppConst.ProductionImgFold;
            return GetFileUrl(_dir, folder, fileID);
        }
        public static List<FileObject> UploadAvatar(string folder, byte[] bytes)
        {
            List<FileObject> listFiles = new List<FileObject>();

            HttpFileCollection filesCollecton = HttpContext.Current.Request.Files;
            if (bytes != null && bytes.Length > 0)
            {
                string newFileName = GetSeriesFileName() + ".jpg";

                // 保存文件
                string newPath = GetFilePath(_rootDir, folder, string.Empty);
                if (!Directory.Exists(newPath))
                    Directory.CreateDirectory(newPath);
                newPath = Path.Combine(newPath, newFileName);
                FileStream fs = new FileStream(newPath, FileMode.OpenOrCreate);
                fs.Write(bytes, 0, bytes.Length);

                // 保存记录
                string publicUri = GetFileUrl(_dir, folder, newFileName);

                FileObject file = new FileObject()
                {
                    ID = newFileName,
                    Size = bytes.Length,
                    PublicUrl = publicUri
                };
                listFiles.Add(file);
            }
            return listFiles;
        }
        public static List<FileObject> Upload(string folder, string fileID = null)
        {
            List<FileObject> listFiles = new List<FileObject>();

            HttpFileCollection filesCollecton = HttpContext.Current.Request.Files;
            if (filesCollecton != null && filesCollecton.Count > 0)
            {
                for (int i = 0; i < filesCollecton.Count; i++)
                {
                    var uploadedFile = filesCollecton[i];
                    string newFileName = fileID;

                    if (!String.IsNullOrEmpty(fileID))
                        DeleteFile(_rootDir, fileID, folder);
                    else
                        newFileName = GetSeriesFileName() + Path.GetExtension(uploadedFile.FileName);

                    // 保存文件
                    string newPath = GetFilePath(_rootDir, folder, string.Empty);
                    if (!Directory.Exists(newPath))
                        Directory.CreateDirectory(newPath);
                    newPath = Path.Combine(newPath, newFileName);
                    uploadedFile.SaveAs(newPath);

                    // 保存记录
                    string contentType = MimeMapping.GetMimeMapping(uploadedFile.FileName);
                    string publicUri = GetFileUrl(_dir, folder, newFileName);

                    FileObject file = new FileObject()
                    {
                        ID = newFileName,
                        Size = uploadedFile.ContentLength,
                        ContentType = contentType,
                        Name = uploadedFile.FileName,
                        PublicUrl = publicUri
                    };
                    listFiles.Add(file);
                }
            }
            return listFiles;
        }


        public static string GetAdministratorAvatar(string fileID)
        {
            if (string.IsNullOrEmpty(fileID))
            {
                return "/Areas/Admin/Content/images/administrator.png";
            }
            string folder = Utils.AppConst.AdministratorAvatarFold;
            return GetFileUrl(_dir, folder, fileID);
        }
    }
}